package com.example.wxchatdemo;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.wxchatdemo.SQLitess.SQLites;
import com.example.wxchatdemo.pojo.WeChat_msgs;
import com.example.wxchatdemo.utils.MyThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class speackActivity extends AppCompatActivity {
    private List<speacking> mData = null;
    private Context mContext;
    private speackingAdapter mAdapter = null;
    private ListView list_animal;
    //上部分
    private Button return_main,show_all;
    private TextView F_name;
    //下部分-输入栏
    private Button emo,send;
    private EditText editText;
    private String my_id,other_id;
    //数据库
    private SQLiteDatabase db;
    private SQLites sqLites;

    private StringBuilder sb;
    private int i = 1;
    //Socket
    private int isclose=0;
    //用户名
     private String f_name;



     //SOCKET
     private Socket socket;
    private PrintWriter printWriter;
    private  int isno;
    BufferedReader bufferedReader = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);
        mContext = speackActivity.this;
        list_animal = (ListView) findViewById(R.id.list_animal);
        //查找上部分内容
        return_main=(Button) findViewById(R.id.return_main);
        show_all=(Button) findViewById(R.id.show_all);
        F_name=(TextView)findViewById(R.id.F_name);
        //查找下部分内容
        emo=(Button) findViewById(R.id.emo);
        send=(Button) findViewById(R.id.send);
        editText=(EditText) findViewById(R.id.editext);
        F_name=(TextView)findViewById(R.id.F_name);
        //创建数据库
        sqLites = new SQLites(mContext, "my.db", null, 1);
        Intent intents = getIntent();
        Bundle bundle=intents.getExtras();

        //对方账号识别；---上一个ativity发送过来的；
        String id = bundle.getString("f_id");
        f_name=bundle.getString("f_name");
        my_id=bundle.getString("my_id");
        F_name.setText(f_name);

        //设置本人的my_id
        //my_id="1";
        //设置对手id
        other_id=id+"";




//创建连接
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket("100.2.33.224", 8086);
                    isno=1;
                    ///*****
                    System.out.println("开启了读写模式");
                    try {

                        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        String msg;//服务器发过来的信息
                        while ((msg = bufferedReader.readLine()) != null) {
                            System.out.println("##=====服务器发送信息是：" + msg);
                            //
                            String finalMsg = msg;
                            //修改当前的ui
                            speackActivity.this.runOnUiThread(new Runnable() {
                                public void run() {
                                 //接收消息
                                    mData.add(new speacking(finalMsg, 789789789+"",other_id+""));
                                    mAdapter = new speackingAdapter((LinkedList<speacking>) mData, mContext,my_id,other_id);
                                    list_animal.setAdapter(mAdapter);
                                    //定位在最后一条
                                    list_animal.setSelection(ListView.FOCUS_DOWN);


                                }
                            });
                            //

                        }
                        System.out.println("你偷懒啊=====");
                    } catch (IOException e) {
                        System.out.println("警告：断开连接！");
                        try {
                            if (!socket.isClosed()) {
                                socket.close();
                            }
                        } catch (IOException e1) {
                            System.out.println("读取线程：关闭socket出现错误");
                        }
                    }
                    // System.exit(1);
                    System.out.println("中心");

                    ////***

                } catch (IOException e) {
                    System.out.println("socket线程出错了");
                    isno=0;
                }//
            }
        }).start();



//数据库查询结果--mysql
      MyThread myThread=new MyThread(my_id,other_id,null,"");
      myThread.start();

        List<WeChat_msgs>  weChat_msgs= null;
        try {
            weChat_msgs = myThread.call();
        } catch (Exception e) {
            e.printStackTrace();
        }


        /*
        SQLiteDatabase dbs = sqLites.getReadableDatabase();
        Cursor cursor =  dbs.rawQuery("SELECT * FROM wechat where youid=? and myid=? ",new String[]{other_id,my_id}      );
        //查询数据库
        System.out.println(cursor.getCount()+"数据库条数");
        //
       List<Map> list=new ArrayList<Map>();


        while (cursor.moveToNext())
        {   //创建map
            Map<String,String> map=new HashMap<String,String>();

            int personid = cursor.getInt(cursor.getColumnIndex("id"));
            int  youid = cursor.getInt(cursor.getColumnIndex("youid"));
            int  myid = cursor.getInt(cursor.getColumnIndex("myid"));
            String contents=cursor.getString(cursor.getColumnIndex("content"));

            map.put("id",personid+"");
            map.put("youid",youid+"");
            map.put("myid",myid+"");
            map.put("content",contents);
            map.put("times","18:00");
            list.add(map);

            System.out.println(youid+" "+"这是对面id"+"--->"+myid);
        }
        cursor.close();//查找数据库*/

        mData = new LinkedList<speacking>();

//查看网络是否异常，网络异常则调用本地数据库；如何继续渲染
try{
    System.out.println("网络是否异常？？？？"+weChat_msgs.size());
}
catch (Exception e){
    System.out.println("speackAcivity==网络异常，连接服务器失败");
    Toast.makeText(speackActivity.this, "网络异常，请查看网络是否畅通", Toast.LENGTH_LONG).show();
//执行查询本地数据库
    weChat_msgs=GetNoW(my_id,other_id);
}
        //根据查出来的数据设置聊天消息位置
        for (int i=0;i<weChat_msgs.size();i++){
            //System.out.println("查到的聊天记录"+weChat_msgs.toString());
            if ("sent".equals(weChat_msgs.get(i).getStatus())){
                // System.out.println("安排在左边");
                // System.out.println("=======>左边"+f_name);
                mData.add(new speacking(weChat_msgs.get(i).getContent()+"", weChat_msgs.get(i).getTimes()+"", weChat_msgs.get(i).getMyid(),weChat_msgs.get(i).getTimes()+""));
                continue;
            }
            //System.out.println("安排在右边");
            // System.out.println(weChat_msgs.get(i).getStatus()+"当前状态是这个-----");
            mData.add(new speacking(weChat_msgs.get(i).getContent()+"", weChat_msgs.get(i).getTimes()+"", weChat_msgs.get(i).getYouid(),weChat_msgs.get(i).getTimes()+""));
        }










//        mData.add(new speacking("我爱你啊啊啊啊ewdweeeeee韦恩韦德 物非人非二分阿人个  七二杠阿二给微软个人情感给企鹅二啊", "18:60",other_id));

       mData.add(new speacking("不是吧，这都不给高分？？？", "3274372842",other_id));

        mAdapter = new speackingAdapter((LinkedList<speacking>) mData, mContext,my_id,other_id);
        list_animal.setAdapter(mAdapter);
        //定位在最后一条
        list_animal.setSelection(ListView.FOCUS_DOWN);



        //返回按钮
        return_main.setOnClickListener(new View.OnClickListener() {
           //

            @Override
            public void onClick(View view) {




                //
                isclose=1;
                //跳转页面
               Intent open_main=new Intent(speackActivity.this,MainActivity.class);
               startActivity(open_main);
//关闭连接socket
                try {
                    socket.close();
                    System.out.println("链接已关闭了socket");
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }
        });

        //查看详情按钮
        show_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



             /*   SQLiteDatabase dbs = sqLites.getReadableDatabase();
                Cursor cursor =  dbs.rawQuery("SELECT * FROM wechat where youid=? and myid=? ",new String[]{other_id,my_id}      );
                //查询数据库

                while (cursor.moveToNext())
                {
                    int personid = cursor.getInt(cursor.getColumnIndex("id"));
                    int  youid = cursor.getInt(cursor.getColumnIndex("youid"));
                    int  myid = cursor.getInt(cursor.getColumnIndex("myid"));
                    String contents=cursor.getString(cursor.getColumnIndex("content"));
                    System.out.println("----------------------------------------------");
                    System.out.println("||"+personid+"----"+youid+"------"+myid+"----"+contents+"||");
                    System.out.println("-----------------------------------------------");
                }
            cursor.close();
            }*/
            }


        });

        //表情按钮
        emo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List list=new ArrayList<WeChat_msgs>();

                SQLiteDatabase dbs = sqLites.getReadableDatabase();
                Cursor cursor =  dbs.rawQuery("SELECT * FROM wechat ",null      );
                //查询数据库
                System.out.println(cursor.getCount()+"数据库条数");
                while (cursor.moveToNext())
                {

                    Long personid = cursor.getLong(cursor.getColumnIndex("id"));
                    int  youid = cursor.getInt(cursor.getColumnIndex("youid"));
                    int  myid = cursor.getInt(cursor.getColumnIndex("myid"));
                    String contents=cursor.getString(cursor.getColumnIndex("content"));
                    long timess = cursor.getLong(cursor.getColumnIndex("times"));
                    String status=cursor.getString(cursor.getColumnIndex("status"));
        list.add(new WeChat_msgs(personid+"",youid+"",myid+"",contents,timess+"",status));
               System.out.println(personid+"----"+"||"+youid+"||"+"---"+"||"+myid+"||"+"-------------"+"||"+contents+"||"+"----"+timess+"---"+status);
                }
                cursor.close();//查找数据库

            }
        });


        //sent按钮点击事件
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取7位的随机数
                Calendar cal= Calendar.getInstance();
                int m=cal.get(Calendar.MONTH);
                int d=cal.get(Calendar.DATE);
                int h=cal.get(Calendar.HOUR_OF_DAY);
                int mi=cal.get(Calendar.MINUTE);
                int s=cal.get(Calendar.SECOND);
                Random rand = new Random();
                int i = rand.nextInt(100);

               // System.out.println("现在随机数"+times);
                long time_no=new Date().getTime();

                if (!"".equals(getContent(editText))) {
                    db = sqLites.getWritableDatabase();
                    //参数依次是：表名，强行插入null值得数据列的列名，一行记录的数据
                    System.out.println("开始执行数据库操作");
                    db.execSQL("INSERT INTO `wechat`(`id`, `youid`, `myid`, `content`, `times`,'status') VALUES (?, ?, ?, ?, ?,?);", new String[]{time_no + "", other_id + "", my_id + "", getContent(editText), time_no+"","sent"});
                    db.execSQL("INSERT INTO `wechat`(`id`, `youid`, `myid`, `content`, `times`,'status') VALUES (?, ?, ?, ?, ?,?);", new String[]{time_no+1 + "", my_id + "", other_id + "", getContent(editText), time_no+"","re"});
                     Sent_msgs(time_no+"",other_id+"",my_id+"",getContent(editText),time_no+"","sent");
                    Sent_msgs(time_no+1+"",my_id+"",other_id+"",getContent(editText),time_no+"","re");
                    System.out.println("发送请求到数据库");
                    //发送消息到服务器
                    if (0!=isno) {

                        try {
                            printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
                        } catch (IOException e) {
                            System.out.println("链接已断开发送消息");
                        }
                        printWriter.println(getContent(editText));

                    }
                    //发送消息到服务器

                    db.close();
                }

                //
                //新增聊天记录---发送信息---判断是否输入是空
                if (!"".equals(getContent(editText)))
                    {
                //获取时间---秒计算
                long timeMillis = System.currentTimeMillis();
                 //生成简单时间
                SimpleDateFormat sdfTwo =new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒E", Locale.getDefault());
                //星期几？
                String time44 = sdfTwo.format(timeMillis);
               // Log.d("test", timeMillis +"  现在的时间44-->:" + time44);
                 //
                mData.add(new speacking(getContent(editText), timeMillis+"",my_id+""));
                mAdapter = new speackingAdapter((LinkedList<speacking>) mData, mContext,my_id,other_id);
                list_animal.setAdapter(mAdapter);
                //刷新数据，并定位在最后一条信息
                list_animal.setSelection(ListView.FOCUS_DOWN);
                //清空输入框内容
                editText.setText("");
                 }else {
                    Toast.makeText(speackActivity.this, "未填写消息，不能发送", Toast.LENGTH_LONG).show();
                }
                    }
                });

        //listview设置不可点击
//        list_animal.setEnabled(false);

    }
    public String getContent(EditText editText){
        return editText.getText().toString();

    }

//发送按钮功能
     int Sent_msgs(String id,String youid,String my_id,String content,String times,String status){
        int msg=0;
//        发送网络请求，并获取数据
                // 开一个线程完成网络请求操作
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        String result = null;
                        OkHttpClient client = new OkHttpClient();

                        Request request = new Request.Builder()
                                .url("http://100.2.33.224:8085/Login?id="+id+"&youid="+youid+"&myid="+my_id+" &content="+content+" &times="+times+"&status="+status ).build();
                                        //数据是：//phone="+phone.getText()+"&name="+username.getText()+"&password="+password.getText())

                        try (Response response = client.newCall(request).execute()) {

                            result = response.body().string();

                            System.out.println("服务器返回消息==》"+result);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }







                }).start();
        return msg;
    }

        //转换json字符串方法
    List<Map<String,String>> TransJSON(String argss){
        //创建返回数据
        List<Map<String,String>> list = new ArrayList<>();
        Map map=new HashMap<String,String >();


        String jsonArray=argss;
        StringBuffer sb=new StringBuffer();
        //需要使用的JSON的parseArray方法，将jsonArray解析为object类型的数组
        JSONArray objects = JSON.parseArray(jsonArray);
        int i=0;
       // for(int i=0;i<objects.size();i++){
        while (i<objects.size()){
            Map map2=new HashMap<String,String >();
            //通过数组下标取到object，使用强转转为JSONObject，之后进行操作
            JSONObject object = (JSONObject) objects.get(i);
            String id = object.getString("id");
            String youid = object.getString("youid");
            String myid= object.getString("myid");
            String content= object.getString("content");
            String times= object.getString("times");
            String status= object.getString("status");
            //System.out.println("TranJson方法结果集"+"id="+id+"---myid--="+myid+"--youid="+youid+"--time="+times+"==="+content);

            //把数据放入map中
            map2.put("id",id);
            map2.put("myid",myid);
            map2.put("youid",youid);
            map2.put("content",content);
            map2.put("times",times);
            map2.put("status",status);
            list.add(map2);
            i++;
        }
        return list;
    }
    //***未使用=从网络查询两条记录
    List<WeChat_msgs> GetMsgs(String youid, String my_id){
        int msg=0;
      List lists = new ArrayList<WeChat_msgs>();

//        发送网络请求，并获取数据
        // 开一个线程完成网络请求操作
       new Thread(new Runnable()
       {

           List listss = new ArrayList<WeChat_msgs>();



            @Override
            public void run() {
                List listsss = new ArrayList<WeChat_msgs>();

                String result = null;
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url("http://100.2.33.224:8085/GetMsgs?youid="+youid+"&myid="+my_id).build();
                //数据是：//phone="+phone.getText()+"&name="+username.getText()+"&password="+password.getText())

                try (Response response = client.newCall(request).execute()) {

                    result = response.body().string();
                    //转化JSON函数
                    List<Map<String, String>> list = TransJSON(result);

                    System.out.println("获得结果集数量"+list.size());
                    //循环取出json
                  //  while (inde<list.size()){
                    for (int i=0;i<list.size();i++){
                        String id=list.get(i).get("id");
                        String myid= list.get(i).get("myid");
                        String youid= list.get(i).get("youid");
                        String content= list.get(i).get("content");
                        String times= list.get(i).get("times");
                       //System.out.println("GetJSon方法结果集"+"id="+id+"---myid--="+myid+"--youid="+youid+"--time="+times+"==="+content);


                        //创建实体类
                        WeChat_msgs weChat_msgs = new WeChat_msgs();
                        weChat_msgs.setId(id);
                        weChat_msgs.setMyid(myid);
                        weChat_msgs.setContent(content);
                        weChat_msgs.setTimes(times);
                        weChat_msgs.setYouid(youid);
                        listsss.add(weChat_msgs);

                        System.out.println("不是最后获取一下长度-----"+listss.size());
                    }




                } catch (IOException e) {
                    e.printStackTrace();
                }

                listss=listsss;   }//run




         }).start();






        System.out.println("最后获取一下长度"+ lists.size());
        return lists;
    }

//无网络情况下，从本地数据库查找信息
    List<WeChat_msgs> GetNoW( String myids,String youids){
        List list=new ArrayList<WeChat_msgs>();

        SQLiteDatabase dbs = sqLites.getReadableDatabase();
        Cursor cursor =  dbs.rawQuery("SELECT * FROM wechat where myid="+myids+" and youid="+youids,null      );
        //查询数据库
        System.out.println(cursor.getCount()+"数据库条数");
        while (cursor.moveToNext())
        {
            Long personid = cursor.getLong(cursor.getColumnIndex("id"));
            int  youid = cursor.getInt(cursor.getColumnIndex("youid"));
            int  myid = cursor.getInt(cursor.getColumnIndex("myid"));
            String contents=cursor.getString(cursor.getColumnIndex("content"));
            long times = cursor.getLong(cursor.getColumnIndex("times"));
            String status=cursor.getString(cursor.getColumnIndex("status"));
            list.add(new WeChat_msgs(personid+"",myid+"",youid+"",times+"",contents+"",status));
            System.out.println(personid+"----"+"||"+youid+"||"+"---"+"||"+myid+"||"+"-------------"+"||"+contents+"||"+"----"+times+"---"+status);
        }
        cursor.close();//查找数据库

        return list;
    }



}
